package com.gcloud.mesh.dcs.chain.huawei;

import com.alibaba.fastjson.JSONObject;
import com.gcloud.mesh.dcs.chain.FilterChain;
import com.gcloud.mesh.dcs.chain.IMigrationStepChain;
import com.gcloud.mesh.dcs.strategy.huawei.ShowServerSolution;
import com.gcloud.mesh.header.param.HuaweiMigrationParam;
import com.huaweicloud.sdk.sms.v3.model.Disk;
import com.huaweicloud.sdk.sms.v3.model.ShowServerResponse;
import com.huaweicloud.sdk.sms.v3.model.TargetDisks;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class GetTargetDisk_2 extends AbstractHuaweiMigrationStep {
    @Override
    public void doExec(String schedulerJobId, String attach, FilterChain filterChain, IMigrationStepChain stepChain) {
        JSONObject jsonObject = JSONObject.parseObject(attach);
        HuaweiMigrationParam huaweiMigrationParam = JSONObject.toJavaObject(jsonObject,HuaweiMigrationParam.class);
        String sourceServerId = jsonObject.getString("sourceServerId");
        HuaweiServerInfo info = getTargetDisk(huaweiMigrationParam.getAccessKey(), huaweiMigrationParam.getSecretKey(), sourceServerId);
        log.info("获取源磁盘成功");
        jsonObject.put("targetDisks",info.getDisks());
        jsonObject.put("osType", info.getOsType());
        filterChain.doExec(schedulerJobId,jsonObject.toString(),filterChain,stepChain);
    }

    @Override
    public String chainName(String attach) {
        return "获取迁移源磁盘信息";
    }

    @Override
    public int getOrder() {
        return 2;
    }

    public HuaweiServerInfo getTargetDisk(String ak, String sk, String sourceServerId){
    	HuaweiServerInfo info = new HuaweiServerInfo();
        log.debug("开始获取源服务器磁盘信息");
        ShowServerSolution showServer = new ShowServerSolution();
        ShowServerResponse res = showServer.showServer(ak, sk, sourceServerId);
        List<Disk> disks = res.getDisks();
        List<TargetDisks> listTargetServerDisks = new ArrayList<>();
        for(Disk disk : disks) {
            listTargetServerDisks.add(
                    new TargetDisks()
                            .withName(disk.getName())
                            .withPhysicalVolumes(disk.getPhysicalVolumes())
                            .withSize(disk.getSize())
                            .withUsedSize(disk.getUsedSize())
            );
        }
        info.setDisks(listTargetServerDisks);
        info.setOsType(res.getOsType());
        log.debug("获取华为云源服务器信息结束");
        return info;
    }
}
